package com.yoomiito.app.ui.order.detail;

import android.os.Bundle;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.yoomiito.app.Constant;
import com.yoomiito.app.R;
import com.yoomiito.app.base.App;
import com.yoomiito.app.base.BaseActivity;
import com.yoomiito.app.model.order.ItemInfo;
import com.yoomiito.app.model.order.OrderDetailGoods;
import com.yoomiito.app.model.order.OrderDetailInfo;
import com.yoomiito.app.ui.college.detail.SubjectDetailActivity;
import com.yoomiito.app.ui.goods.GoodsInfoActivity;
import com.yoomiito.app.ui.goods.NewGoodsInfoActivity;
import com.yoomiito.app.utils.AllCode;
import com.yoomiito.app.utils.DataUtils;
import com.yoomiito.app.utils.DensityUtil;
import com.yoomiito.app.utils.EventMessage;
import com.yoomiito.app.utils.L;
import com.yoomiito.app.utils.SpannableUtils;
import com.yoomiito.app.utils.Type;
import com.yoomiito.app.utils.YMToast;
import com.yoomiito.app.widget.SpacingDecoration;
import com.yoomiito.app.widget.dialog.PayDialog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 订单详情
 */
public class OrderInfoActivity extends BaseActivity<OrderInfoPresenter> {

    @BindView(R.id.tv_center)
    TextView titleTv;
    @BindView(R.id.rcy)
    RecyclerView mRecyclerView;

    LinearLayout bgLl;
    TextView orderStatusTv;
    ImageView iconIv;
    TextView nameTv;
    TextView telTv;
    TextView addressTv;
    @BindView(R.id.act_order_info_ll)
    View sureGetGoodsView;
    @BindView(R.id.pay)
    TextView mPayTv;
    @BindView(R.id.cancel_order)
    TextView mCancelOrderTv;
    @BindView(R.id.act_order_info_btn)
    Button mSureGetGoodsBtn;
    @BindView(R.id.un_pay_money)
    TextView mUnPayTv;


    private String mOrderId;
    private int orderType;
    private OrderDetailInfo mDetailInfo;
    private PayDialog payDialog;
    public String mQueryOrderID;
    public String pay_type;//支付类型
    private OrderInfoAdapter adapter;
    private ItemInfoAdapter itemInfoAdapter_1;
    private ItemInfoAdapter itemInfoAdapter_2;
    private View addressView;
    private int mGoodsType = 0;//仅用来区分送多多礼包--7 和 赠品--8

    @Override
    public int getLayoutId() {
        return R.layout.act_order_info;
    }

    @Override
    public OrderInfoPresenter newP() {
        return new OrderInfoPresenter(App.mAppConfig);
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        titleTv.setVisibility(View.VISIBLE);
        titleTv.setText("订单详情");
        mOrderId = getIntent().getStringExtra(Constant.ID);
        mGoodsType = getIntent().getIntExtra(Constant.KEY, 0);
        orderType = getIntent().getIntExtra(Constant.TYPE, 0);
        initView();
        showLoading();
        getP().getOrderInfo(mOrderId, orderType);
    }

    private void initView() {
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.addItemDecoration(new SpacingDecoration(0, DensityUtil.dp2px(10), false));
        adapter = new OrderInfoAdapter(null);
//        adapter.setOnItemClickListener((adapter1, view, position) -> {
//            OrderDetailGoods info = (OrderDetailGoods) adapter1.getData().get(position);
//            if (mGoodsType==7||mGoodsType==8){//送多多 赠品不可点击
//                return;
//            }
//            int goodsType = DataUtils.INSTANCE.getGoodsType(Type.ServiceConfigGoodsType.GoodsMainTypePrivateGoods,info.getProduct_type());
//            switch (goodsType){
//                case Type.GoodsType.BaoPin:
//                case Type.GoodsType.YouPin:
//                case Type.GoodsType.Gift:
//                    NewGoodsInfoActivity.Companion.toGoodsInfo(OrderInfoActivity.this,info.getProduct_id()+"",
//                            Type.ServiceConfigGoodsType.GoodsMainTypePrivateGoods+"");
//                    break;
//                case Type.GoodsType.College:
//                    SubjectDetailActivity.Companion.start(this,Long.valueOf(info.getProduct_id()),true,Long.valueOf(info.getNew_product_id()));
//                    break;
//                    default:
//                        GoodsInfoActivity.toGoodsInfo(OrderInfoActivity.this,info.getProduct_id()+"",goodsType);
//                        break;
//            }
//        });

        View headerView = LayoutInflater.from(this).inflate(R.layout.item_order_detail_header, null, false);
        addressView = headerView.findViewById(R.id.act_buy_goods_address);
        headerView.findViewById(R.id.item_address_iv_2).setVisibility(View.GONE);
        orderStatusTv = headerView.findViewById(R.id.act_order_info_status);
        nameTv = headerView.findViewById(R.id.item_address_name);
        telTv = headerView.findViewById(R.id.item_address_tel);
        addressTv = headerView.findViewById(R.id.item_address_text);
        iconIv = headerView.findViewById(R.id.act_order_info_ic);
        bgLl = headerView.findViewById(R.id.act_order_info_bg);
        adapter.setHeaderView(headerView);

        View footView = LayoutInflater.from(context).inflate(R.layout.item_order_detail_footer, null, false);
        RecyclerView rcy_1 = footView.findViewById(R.id.rcy_1);
        rcy_1.setLayoutManager(new LinearLayoutManager(this));
        rcy_1.addItemDecoration(new SpacingDecoration(0, DensityUtil.dp2px(10), false));
        itemInfoAdapter_1 = new ItemInfoAdapter(null);
        rcy_1.setAdapter(itemInfoAdapter_1);

        RecyclerView rcy_2 = footView.findViewById(R.id.rcy_2);
        rcy_2.setLayoutManager(new LinearLayoutManager(this));
        rcy_2.addItemDecoration(new SpacingDecoration(0, DensityUtil.dp2px(10), false));
        itemInfoAdapter_2 = new ItemInfoAdapter(null);
        rcy_2.setAdapter(itemInfoAdapter_2);
        adapter.setFooterView(footView);

        mRecyclerView.setAdapter(adapter);

    }

    @OnClick({R.id.iv_back_left, R.id.act_order_info_btn, R.id.cancel_order, R.id.pay})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back_left:
                finish();
                break;
//            case R.id.item_wuliu_order_copy://单号复制
////                String id = wuliuIdTv.getText().toString().trim();
////                if (id.length() <= 5) {
////                    return;
////                }
////                String orderId = id.substring(5);
////                AllUtils.copyText(this, orderId);
////                YMToast.showText("复制成功");
//                break;
//            case R.id.item_order_new_info://查看物流信息
//                Router.newIntent(this)
//                        .putParcelable(Constant.DATA, mDetailInfo)
//                        .to(WuLIuActivity.class)
//                        .launch();
//                break;
            case R.id.act_order_info_btn://确认收货
                showLoading();
                getP().confirmOrder(String.valueOf(mDetailInfo.getId()), (mDetailInfo.getOrder_type() == 6 || mDetailInfo.getOrder_type() == 7) ? (mDetailInfo.getOrder_type() + 1) : mDetailInfo.getOrder_type());
                break;
            case R.id.cancel_order://取消订单
                getP().cancelOrder(mDetailInfo.getOrder_type(), mOrderId);
                break;
            case R.id.pay://去支付
                if (mGoodsType == 7 || mGoodsType == 8) {//送多多 赠品不可点击  送多多的小程序订单直接拦截
                    YMToast.showCenterToast("小程序订单，请去小程序支付。");
                    return;
                }
                showPayDialog();
                break;
        }
    }

    /**
     * 处理获取数据失败
     */
    public void getDataFail() {
        dismissLoading();
        finish();
    }

    public void setOrderInfo(OrderDetailInfo info) {
        dismissLoading();
        mDetailInfo = info;
//        //订单状态  0 待支付  1待发货、2待收货、3确认收货、4已结算 不再显示已结算状态、5已失效 6已完成  7 已退货
        orderStatusTv.setText(info.statusStr);
        switch (info.getStatus()) {
            case 0:
                iconIv.setImageResource(R.drawable.icon_unpay);
                mUnPayTv.setText("待支付 ¥" + info.getCash_paid());
                sureGetGoodsView.setVisibility(View.VISIBLE);
                mCancelOrderTv.setVisibility(View.VISIBLE);
                mPayTv.setVisibility(View.VISIBLE);
                break;
            case 1:
                iconIv.setImageResource(R.drawable.wait);
                if (info.display == 0) {
                    sureGetGoodsView.setVisibility(View.GONE);
                    mCancelOrderTv.setVisibility(View.GONE);
                } else {
                    sureGetGoodsView.setVisibility(View.VISIBLE);
                    mCancelOrderTv.setVisibility(View.VISIBLE);
                }
                mSureGetGoodsBtn.setVisibility(View.GONE);
                mUnPayTv.setVisibility(View.GONE);
                mPayTv.setVisibility(View.GONE);
                break;
            case 2://布局已默认
                sureGetGoodsView.setVisibility(View.VISIBLE);
                mSureGetGoodsBtn.setVisibility(View.VISIBLE);
                mUnPayTv.setVisibility(View.GONE);
                mCancelOrderTv.setVisibility(View.GONE);
                mPayTv.setVisibility(View.GONE);
                break;
            case 3:
            case 6:
                bgLl.setBackgroundResource(R.color.color_order_bg);
                iconIv.setImageResource(R.drawable.received_goods);
                sureGetGoodsView.setVisibility(View.GONE);
                break;
            case 4:
                bgLl.setBackgroundResource(R.color.color_blue);
                iconIv.setImageResource(R.drawable.already_settled_2);
                sureGetGoodsView.setVisibility(View.GONE);
                break;
            case 5:
            case 7:
                bgLl.setBackgroundResource(R.color.color_balk_999999);
                iconIv.setVisibility(View.GONE);
                sureGetGoodsView.setVisibility(View.GONE);
                break;
        }
        if (mDetailInfo.getOrder_type() == 4) {//课程不显示地址
            addressView.setVisibility(View.GONE);
        }

//        //地址信息
        nameTv.setText(info.getConsignee());
        telTv.setText(info.getMobile());
        addressTv.setText(info.province + " " + info.city + " " + info.county + " " + info.getAddress());


        List<OrderDetailGoods> list = new ArrayList<>();
        OrderDetailGoods orderDetailGoods = new OrderDetailGoods();
        orderDetailGoods.setProduct_name(info.productName);
        orderDetailGoods.setProduct_img(info.banner);
        orderDetailGoods.setAmount(info.price);
        orderDetailGoods.setNum(Integer.parseInt(info.getNum()));
        orderDetailGoods.setSn(info.getId());
        orderDetailGoods.setNote(info.getNote());
        orderDetailGoods.setExpressState(info.getExpressState());
        orderDetailGoods.setExpressInfo(info.getExpressInfo());
        orderDetailGoods.setTrack_no(info.getTrack_no());
        orderDetailGoods.setExpress_company(info.name);
        orderDetailGoods.setStatusStr(info.statusStr);

        list.add(orderDetailGoods);

        adapter.setNewData(list);

        //info.getPay_type() 1 微信 2支付宝 3余额 4余额加微信 5余额加支付宝'
        List<ItemInfo> itemInfos_1 = new ArrayList<>();
        itemInfos_1.add(new ItemInfo("实收款", "¥" + info.totalMoney));
        if (!SpannableUtils.isEmptyOr0(info.getYo_money_paid())) {
            itemInfos_1.add(new ItemInfo("优米抵扣", "-¥" + info.getYo_money_paid()));
        }
        if (!SpannableUtils.isEmptyOr0(info.getDeduction_account_paid())) {
            itemInfos_1.add(new ItemInfo("余额抵扣", "-¥" + info.getDeduction_account_paid()));
        }
        itemInfos_1.add(new ItemInfo("订单总价", "¥" + info.totalMoney, true));
        if (0 == info.getStatus()) {//待支付订单
            if (!SpannableUtils.isEmptyOr0(info.getBalance_paid())) {
                itemInfos_1.add(new ItemInfo("余额支付", "¥" + info.getBalance_paid()));
            }
        } else {
            if ("1".equals(info.getPay_type())) {
                itemInfos_1.add(new ItemInfo("微信支付", "¥" + info.getCash_paid()));
            } else if ("2".equals(info.getPay_type())) {
                itemInfos_1.add(new ItemInfo("支付宝支付", "¥" + info.getCash_paid()));
            } else if ("3".equals(info.getPay_type())) {
                itemInfos_1.add(new ItemInfo("余额支付", "¥" + info.getBalance_paid()));
            } else if ("4".equals(info.getPay_type())) {
                itemInfos_1.add(new ItemInfo("余额支付", "¥" + info.getBalance_paid()));
                itemInfos_1.add(new ItemInfo("微信支付", "¥" + info.getCash_paid()));
            } else if ("5".equals(info.getPay_type())) {
                itemInfos_1.add(new ItemInfo("余额支付", "¥" + info.getBalance_paid()));
                itemInfos_1.add(new ItemInfo("支付宝支付", "¥" + info.getCash_paid()));
            } else if ("6".equals(info.getPay_type())) {
                itemInfos_1.add(new ItemInfo("电子币支付", "¥" + info.getCash_paid()));
            } else if ("7".equals(info.getPay_type())) {
                itemInfos_1.add(new ItemInfo("余额支付", "¥" + info.getBalance_paid()));
                itemInfos_1.add(new ItemInfo("电子币支付", "¥" + info.getCash_paid()));
            }
        }
        itemInfoAdapter_1.setNewData(itemInfos_1);

        List<ItemInfo> itemInfos_2 = new ArrayList<>();
        itemInfos_2.add(new ItemInfo("下单时间：" + info.getCtime(), ""));
        if(!TextUtils.isEmpty(info.shippedTime)){
            itemInfos_2.add(new ItemInfo("发货时间：" + info.shippedTime, ""));
        }
        if(!TextUtils.isEmpty(info.confirmTime)){
            itemInfos_2.add(new ItemInfo("发货时间：" + info.confirmTime, ""));
        }

        //        itemInfos_2.add(new ItemInfo("付款时间：" + (TextUtils.isEmpty(info.getPaid_time()) ? "" : info.getPaid_time()), ""));
//        if ((info.getAcode()==null||info.getAcode().size()==0)&&info.getOrder_detail().size() == 1) {//没有激活码 或 只有一个详情 则显示收发货时间
//            itemInfos_2.add(new ItemInfo("发货时间：" + (TextUtils.isEmpty(info.getShipped_time()) ? "" : info.getShipped_time()), ""));
//            itemInfos_2.add(new ItemInfo("收货时间：" + (TextUtils.isEmpty(info.getConfirm_time()) ? "" : info.getConfirm_time()), ""));
//        }

        itemInfoAdapter_2.setNewData(itemInfos_2);
    }

    public void confirmOrder(boolean isSuccess) {
        showToast(isSuccess ? "确认收货成功" : "确认收货失败");
        dismissLoading();
        if (isSuccess) {
//            sureGetGoodsView.setVisibility(View.GONE);
            getP().getOrderInfo(mOrderId, orderType);
            notifyUpdateData();
        }
    }

    //支付弹窗
    public void showPayDialog() {
        if (payDialog == null) {
            payDialog = new PayDialog(this);
            payDialog.hideMoneyPay();
            payDialog.setOnResultListener((moneyPay, wxPay, aliPay, offline,quick, dismiss) -> {
                if (dismiss) return;
                payDialog.dismiss();
                showLoading();
                getP().pay(String.valueOf(mDetailInfo.getId()), wxPay, aliPay, mDetailInfo.getBalance_paid(),
                        (mDetailInfo.getOrder_type() == 6 || mDetailInfo.getOrder_type() == 7) ? (mDetailInfo.getOrder_type() + 1) : mDetailInfo.getOrder_type(),
                        "", mDetailInfo.getYo_money_paid());
            });
        }
        payDialog.setPayMoney("¥" + mDetailInfo.getCash_paid());
        payDialog.show();
    }

    //获取到微信结果后 查询订单状态
    @Subscribe
    public void registerQueryPayResult(EventMessage eventMessage) {
        if (Constant.PAY_RESULT.equals(eventMessage.getEventType())) {
            if (TextUtils.isEmpty(mQueryOrderID)) {
                showToast("订单状态异常");
                return;
            }
            showLoading();
            getP().queryOrder(mQueryOrderID, pay_type);
        }
    }

    public void updateOrderInfo() {
        showLoading();
        getP().getOrderInfo(mOrderId, orderType);
        notifyUpdateData();
    }

    //根据订单状态 跳到支付结果
    public void payResult(EventMessage eventMessage) {
        dismissLoading();
//        if ("wxpay".equals(pay_type)){
//            TouchUtils.onBuyEvent(eventId,
//                    UserInfoConfig.getRoleId(),
//                    UserInfoConfig.getAgent(),
//                    AllCode.Fail == eventMessage.getCode() ? "wx_pay_fail" : "wx_pay_success");
//        }
        if (AllCode.Success == eventMessage.getCode()) {
            updateOrderInfo();
        }
        notifyUpdateData();
    }

    private void notifyUpdateData() {
        L.i("订单详情支付完成：" + AllCode.UPDATE_DATA + "  " + orderType);
        EventMessage eventMessage = new EventMessage();
        eventMessage.setEventType(AllCode.UPDATE_DATA);
        eventMessage.setGoodsType(orderType);
        EventBus.getDefault().post(eventMessage);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
